import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/datacenter/config_data_center.dart';
import 'package:flutterlib/common/localization/default_localizations.dart';
import 'package:flutterlib/common/style/meterial_design_icons.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/common/utils/navigator_utils.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/interest/interest_bean.dart';
import 'package:flutterlib/pages/interest/viewmodel/interest_store.dart';
import 'package:flutterlib/pages/post/list/post_list_normal_widget_page.dart';
import 'package:flutterlib/widgets/intro/flutter_intro.dart';
import 'package:flutterlib/widgets/quhui_tabbar_widget.dart';
import 'package:flutterlib/widgets/round_underline_tabindicator.dart';
import 'package:mobx/mobx.dart';
import 'package:thrio/thrio.dart';

//用于加载内部继承上下拉的页面state的外部容器页面，
//适用于带tabbar，内部是list的页面的改造
class Page extends StatefulWidget {
  Page({Key key}) : super(key: key);

  @override
  PageState createState() => PageState();
}



class PageState extends State<Page>
    with SingleTickerProviderStateMixin {
  final SettingsStore store =
      Provider.of<SettingsStore>(currentContext, listen: false);
  InterestStore interestStore = InterestStore();
  int _tabIndex = 0;
  List<Widget> tabPageView = new List();
  List<Widget> tabViews = new List();
  Map<int, PostNormalListWidgetPage> pages = {};

  Intro intro = Intro(
    /// 总共的引导页数量，必传
    stepCount: 1,

    /// 高亮区域与 widget 的内边距
    padding: EdgeInsets.all(8),

    /// 高亮区域的圆角半径
    borderRadius: BorderRadius.all(Radius.circular(4)),

    /// 使用库默认提供的 useDefaultTheme 可以快速构建引导页
    /// 需要自定义引导页样式和内容，需要自己实现 widgetBuilder 方法
    widgetBuilder: StepWidgetBuilder.useDefaultTheme(
      /// 提示文本
      texts: [
        '这里可以发现兴趣图片，文章相互点赞和图片相互喜欢都会加为好友哦',
      ],
      buttonTextBuilder: (int currentStepIndex, int stepCount){
        return "知道了";

      },
    ),
  );

  @override
  void initState() {
    super.initState();
    trueDebugPrint("fluttermobx postpage init");

    final allInterestFromStore = allInterestsFromSP;

    allInterestFromStore.asMap().forEach((index, element) {
      pages[element.id] = new PostNormalListWidgetPage(
        key: ValueKey(element.id),
        name: element.name,
        interestId: element.id,
        type: 2,
      );
    });
    tabPageView.add(new PostNormalListWidgetPage(
      name: "全部",
      interestId: 0,
      type: 0,
    ));
    tabViews.add(renderItem("全部", 0));
    var bool = SpUtils.getBool('show_post_intro', defValue: false);
    if(!bool) {
      Timer(Duration(microseconds: 0), () {
        intro.start(context);
        SpUtils.putBool('show_post_intro', true);
      });
    }
  }

  renderItem(String item, int i) {
    return VgTab(
      child: new Text(
        item,
        style: QuhuiConstant.smallSubText,
        maxLines: 1,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    print(context.widget.toStringShort());

    return Observer(builder: (_) {
      final allInterestFromStore = allInterestsFromSP;
      var myInterests = store.interests;
      var allInterestOrdered = <InterestBean>[];

      //如果用户自己操作过
      List<InterestBean> objectList =
          SpUtils.getObjList("interest_order", (v) => InterestBean.fromJson(v));

      if (objectList != null && objectList.isNotEmpty) {
        trueDebugPrint("fluttermobx" +
            "get order interest from sp" +
            objectList.length.toString());
        allInterestOrdered = objectList;
      } else {
        var myInterestMap = {};
        myInterests
            .forEach((interest) => myInterestMap[interest.id] = interest);
        allInterestFromStore
            .removeWhere((interest) => myInterestMap.containsKey(interest.id));
        allInterestOrdered.addAll(myInterests);
        allInterestOrdered.addAll(allInterestFromStore);
      }

      tabPageView.removeRange(1, tabPageView.length);
      tabViews.removeRange(1, tabViews.length);
      allInterestOrdered.asMap().forEach((index, element) {
        tabPageView.add(pages[element.id]);
        tabViews.add(renderItem(element.name, index));
      });

      ///绘制顶部 tab 控件
      return new QuhuiTabBarWidget(
        key: ValueKey(context.widget.toStringShort()),
        type: TabType.top,
        tabBarType: 3,
        onMorePress: () {
          ThrioNavigator.push(
              poppedResult: (result) {
                setState(() {
                  trueDebugPrint("sortinterestpage back + ${result.toString()}",
                      );
                });
              },
              url: '/interest/sort');
          // NavigatorUtils.NavigatorRouter(context, SortInterestPage());
        },
        tabItems: tabViews,
        resizeToAvoidBottomPadding: false,
        tabViews: tabPageView,
        backgroundColor: QuhuiColors.white,
        indicatorColor: QuhuiColors.mainThemeColor,
        // floatingActionButton: FloatingActionButton(
        //     child: Icon(MIcon.add),
        //     onPressed: () {
        //       if (isLogin) {
        //         NavigatorUtils.gotoActionSelectPage(context);
        //       } else {
        //         NavigatorUtils.goLogin(context);
        //       }
        //     }),
        title: getSearchBarUI(),
        onPageChanged: (index) {
          _tabIndex = index;
        },
      );
    });
  }

  Widget getSearchBarUI() {
    return Flex(
      direction: Axis.horizontal,
      children: <Widget>[
        Expanded(
          flex: 5,
          child: Container(
            margin: EdgeInsets.only(right: 10, left: 10),
            decoration: BoxDecoration(
              color: QuhuiColors.grayColor,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              children: [
                SizedBox(
                  width: 25,
                  height: 25,
                  child: Icon(
                    MIcon.search,
                    size: 14,
                    color: Color(0xFF999999),
                  ),
                ),
                InkWell(
                  onTap: (){
                    NavigatorUtils.gotoPostSearch(context, '');
                  },
                  child: Text(
                    QuhuiLocalizations.i18n(context).search_hint,
                    style: TextStyle(
                      fontSize: 12,
                      color: QuhuiColors.subGrayColor,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        Expanded(
          flex: 1,
          child: InkWell(
            key: intro.keys[0],
            onTap: (){
              if (!isLogin) {
                NavigatorUtils.goLogin(context);
                return;
              }
              NavigatorUtils.goPostCard(context);
            },
            child: Container(
              decoration: BoxDecoration(
                color: QuhuiColors.mainThemeColor,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Align(
                alignment: Alignment.center,
                child: Text(
                  "趣图",
                  style: QuhuiConstant.middleTextWhite,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  int getInterestId() {
    if (_tabIndex == 0) {
      return 0;
    }
    var interests = store.interests;
    return interests[_tabIndex - 1]?.id;
  }
}
